
#include <signal.h>

#include <iostream>

#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/HttpMessage.h>
#include <workflow/HttpUtil.h>
using std::cout;
using std::endl;
using std::string;

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf(">> sig num %d is comming\n", num);
    //调用一次done方法，计数器的值减1
    waitGroup.done();
}

//4. 回调函数的实现
void httpCallback(WFHttpTask * httptask)
{
    printf("httpCallback is running\n");
    //1. 对任务的状态进行检测
    int state = httptask->get_state();
    int error = httptask->get_error();
    switch(state) {
    case WFT_STATE_SYS_ERROR:
        printf("system error: %s\n", strerror(error)); break;
    case WFT_STATE_DNS_ERROR:
        printf("dns error: %s\n", gai_strerror(error)); break;
    case WFT_STATE_SUCCESS:
        break;
    }
    if(state != WFT_STATE_SUCCESS) {
        printf("error occurs!\n");
        return;
    }
    //2. 对HttpRequest进行遍历
    printf("task is ok!\n");
    auto req = httptask->get_req();
    //请求报文的起始行
    printf("%s %s %s\n", req->get_method(),
            req->get_request_uri(),
            req->get_http_version());
    //请求报文的首部字段, 借助于迭代器来访问
    protocol::HttpHeaderCursor cursor(req);
    string name, value;
    while(cursor.next(name, value)) {
        cout << name << ": " << value << endl;
    }
    printf("\r\n\r\n");
    //3. 对HttpResponse进行遍历
    auto resp = httptask->get_resp();
    //响应报文的起始行
    printf("%s %s %s\n", resp->get_http_version(),
            resp->get_status_code(),
            resp->get_reason_phrase());

    //响应报文的首部字段, 借助于迭代器来访问
    protocol::HttpHeaderCursor cursor2(resp);
    while(cursor2.next(name, value)) {
        cout << name << ": " << value << endl;
    }
    printf("\r\n");
    //获取响应报文的消息体
    const void * pbody = nullptr;
    size_t size = 0;
    //通过get_parsed_body函数修改pbody的指向
    resp->get_parsed_body(&pbody, &size);
    string body((const char *)pbody, size);
    cout << body << endl;
}

void test0()
{
    signal(SIGINT, sighandler);
    //1. 创建HttpTask
    //1.1 对于URI而言，其格式是要合法的;
    //如果不是合法的URI，任务执行时会报错
    //string url = "www.baidu.com";

    //1.2 当URI合法时，但DNS服务器无法解析的URI
    //string url = "http://wwwwwwww.baicom";
    //1.3 当URI合法且DNS服务器能够解析
    //string url = "http://www.baidu.com";
    string url = "http://localhost";
    auto httpTask = WFTaskFactory::create_http_task(url, 1, 1, httpCallback);
    //2. 设置任务的属性
    httpTask->get_req()->add_header_pair("User-Agent", "Workflow Client");
    httpTask->get_req()->add_header_pair("Accept", "text/html");
    
    //3. 启动HttpTask任务，交给框架调度执行
    httpTask->start();

    //当调用wait方法会阻塞当前线程
    waitGroup.wait();
    cout << "test0 exit" << endl;
}


int main()
{
    test0();
    return 0;
}

